﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Web;
using System.IO;

namespace AndersLiu.CnblogsIng
{
	class IngMobileClient
	{
		public static void Send(string verifyCode, string content)
		{
			System.Threading.Thread.Sleep(10);

			if (verifyCode == null)
				throw new ArgumentNullException("options");

			if (content == null)
				throw new ArgumentNullException("content");

			lock (SyncRoot)
			{
				var str = string.Format(ContentPattern, HttpUtility.UrlEncode(verifyCode), HttpUtility.UrlEncode(content));
				var data = ContentEncoding.GetBytes(str);

				var request = (HttpWebRequest)HttpWebRequest.Create(ServerPath);
				request.Method = @"POST";
				request.UserAgent = @"Anders Liu Robot Agent";
				request.ContentType = @"application/x-www-form-urlencoded";
				request.ContentLength = data.Length;

				using (var stream = request.GetRequestStream())
				{
					stream.Write(data, 0, data.Length);
					stream.Close();
				}

				var response = request.GetResponse();
				using (var stream = response.GetResponseStream())
				{
					using (var reader = new StreamReader(stream))
					{
						reader.ReadToEnd();
					}
				}
			}
		}

		const string ServerPath = @"http://space.cnblogs.com/mi";
		const string ContentPattern = @"__VIEWSTATE=&txbCode={0}&txbContent={1}&chkIsSave=off&btnSubmint=%E6%8F%90%E4%BA%A4";

		static readonly object SyncRoot = new object();
		static readonly Encoding ContentEncoding = Encoding.ASCII;
	}
}
